package com.example.firstdemo.ui.screens.components

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.tooling.preview.Preview
import com.example.firstdemo.ui.theme.AppTheme
import com.github.panpf.zoomimage.GlideZoomAsyncImage
import com.github.panpf.zoomimage.compose.glide.ExperimentalGlideComposeApi

class ZoomableImageState() {
    var visible by mutableStateOf(false)
        private set
    var url by mutableStateOf<String?>(null)
        private set

    fun open(url: String) {
        this.url = url
        visible = true
    }

    fun close() {
        visible = false
        this.url = null
    }
}

@OptIn(ExperimentalGlideComposeApi::class)
@Composable
fun ZoomableImage(state: ZoomableImageState) {
    AnimatedVisibility(
        visible = state.visible,
        enter = fadeIn(),
        exit = fadeOut()
    ) {
        Box(
            contentAlignment = Alignment.Center,
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Black.copy(alpha = 0.6f))
        ) {
            GlideZoomAsyncImage(
                model = state.url,
                contentDescription = "view image",
                contentScale = ContentScale.Fit,
                modifier = Modifier.fillMaxSize(),
                onTap = {
                    state.close()
                }
            )
        }
    }
}


@Preview(
    showSystemUi = true
)
@Composable
fun ZoomableImagePreview() {
    AppTheme {
        Surface {
            Box(
                contentAlignment = Alignment.Center,
                modifier = Modifier.fillMaxSize()
            ) {
                val state = remember { ZoomableImageState() }
                state.open("https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg")
                ZoomableImage(state)
            }
        }
    }
}